package com.silverbox.sweeporder.controller.shopcart;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.silverbox.sweeporder.controller.shopcart.entryvo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.silverbox.core.result.CoreResponse;
import com.silverbox.core.result.CoreResponse.StatusInfo;
import com.silverbox.core.util.StringUtils;
import com.silverbox.core.util.Utils;
import com.silverbox.sweeporder.controller.shopcart.outvo.IndexCartVO;
import com.silverbox.sweeporder.controller.shopcart.outvo.SaveShopCartVO;
import com.silverbox.sweeporder.controller.shopcart.outvo.ShopCartVO;
import com.silverbox.sweeporder.service.shopcart.ShopCartService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 购物车 ClassName: ShopCartController
 * 
 * @author litao
 * @date 2018年1月2日
 */
@Controller
@RequestMapping("shopCart")
@Api(tags = { "购物车接口" })
public class ShopCartController {
	@Autowired
	private ShopCartService shopCartService;

	@RequestMapping(value = "getShopCartByIndex", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取点餐页面购物车中商品(可调用)")
	public CoreResponse<IndexCartVO> getShopCartbyIndex(ShopCartIndexQueryDto shopCartIndexQueryVo) {

		CoreResponse<IndexCartVO> res = new CoreResponse<IndexCartVO>();

		if(shopCartIndexQueryVo.getStoreId()==null || StringUtils.isEmpty(shopCartIndexQueryVo.getBuyerId())){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("请检查参数！参数异常");
			return res;
		}
		//查询店铺购物车商品数据（点餐页面数据封装）
		res = shopCartService.getShopCartbyIndex(shopCartIndexQueryVo);
		return res;
	}

	@RequestMapping(value = "getShopCartByPage", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取购物车页面中的商品(可调用)")
	public CoreResponse<ShopCartVO> getShopCartbyPage(HttpServletRequest request, ShopCartPageQueryDto shopCartPageQueryVo) {

		CoreResponse<ShopCartVO> res = new CoreResponse<ShopCartVO>();
		
		if (StringUtils.isEmpty(shopCartPageQueryVo.getBuyerId())) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("用户id参数异常");
			return res;
		}
		if (shopCartPageQueryVo.getStoreId() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("店铺id参数异常");
			return res;
		}
		if (shopCartPageQueryVo.getIsOut() == null && shopCartPageQueryVo.getClientOrderMode()==null) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("是否整单打包扫码下单必传");
			return res;
		}
		//判断调用接口来源是否是微信
		String userAgent = request.getHeader("User-Agent").toLowerCase();
		Integer clientType = Utils.getClientType(userAgent);
		res = shopCartService.getShopCartbyPage(shopCartPageQueryVo,clientType);
		return res;
	}

	@RequestMapping(value = "saveShopCart", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "添加商品到购物车(可调用)")
	public CoreResponse<SaveShopCartVO> saveShopCart(HttpSession session, HttpServletRequest request,
			@RequestBody(required = true) SaveShopCartEntryVO goodsCartVO) {

		CoreResponse<SaveShopCartVO> res = new CoreResponse<SaveShopCartVO>();
		CoreResponse<StatusInfo> statusInfo = saveGoodsCartCheckParam(goodsCartVO);
		if(statusInfo!=null){
			res.setStatusInfo(statusInfo.getStatusInfo());
			res.setMsg(statusInfo.getSubMsg());
			return res;
		}
		
		if(goodsCartVO.getIsWeight() ==null){
			goodsCartVO.setIsWeight(0);
		}
		if(goodsCartVO.getIsPackage()==null){
			goodsCartVO.setIsPackage(0);
		}
		goodsCartVO.setGoodsDesc("");
		if (Utils.isEmpty(goodsCartVO.getPropIds())) {
			goodsCartVO.setPropIds("");
		}
		if(Utils.isEmpty(goodsCartVO.getImagePath())){
			goodsCartVO.setImagePath("res/imggoodspic.png");
		}
		//goodscart表分类名称的字段长度32位，商家后台设置255，
		if (!StringUtils.isEmpty(goodsCartVO.getCategoryName()) && goodsCartVO.getCategoryName().length() > 32) {
			goodsCartVO.setCategoryName(goodsCartVO.getCategoryName().substring(0, 32));
		}
		res = shopCartService.saveOrUpdateShopCartV2(goodsCartVO);
		return res;
	}
	private CoreResponse<StatusInfo> saveGoodsCartCheckParam(SaveShopCartEntryVO goodsCartVO) {
		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		if(goodsCartVO==null || goodsCartVO.getStoreId()==null){
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("店铺id参数有误");
			return res;
		}
		if (goodsCartVO.getUserInfo()==null || (StringUtils.isEmpty(goodsCartVO.getUserInfo().getBuyerId()))) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("顾客信息参数有误");
			return res;
		}
		if (goodsCartVO.getGoodsId() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("商品goodsId参数有误");
			return res;
		}
		if (goodsCartVO.getSizeId() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("商品sizeId参数有误");
			return res;
		}
		if (goodsCartVO.getCategoryId() == null || Utils.isEmpty(goodsCartVO.getCategoryName())) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("商品categoryId或categoryName参数有误");
			return res;
		}
		if (goodsCartVO.getBuyPrice() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("商品buyPrice参数有误");
			return res;
		}
//		if (goodsCartVO.getOriginalPrice() == null) {
//			res.setStatusInfo(StatusInfo.ERROR_40001);
//			res.setSubMsg("商品OriginalPrice参数有误");
//			return res;
//		}
		if (StringUtils.isEmpty(goodsCartVO.getGoodsName())) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("商品goodsName参数有误");
			return res;
		}
		if (goodsCartVO.getBuyCount() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("商品buyCount参数有误");
			return res;
		}
		if ((new Integer(2).equals(goodsCartVO.getIsPackage()) && CollectionUtils.isEmpty(goodsCartVO.getDetails()))) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("商品details参数有误");
			return res;
		}
		return null;
	}
	
	@RequestMapping(value = "deleteShopCart", method = RequestMethod.POST)
	
	@ResponseBody
	@ApiOperation(value = "清空购物车中所有商品(可调用)")
	public CoreResponse<StatusInfo> deleteShopCart(HttpSession session,
			@RequestBody(required = true) DeleteCartEntryVO deleteCartEntry) {

		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		if (deleteCartEntry == null || deleteCartEntry.getStoreId() == null
				|| StringUtils.isEmpty(deleteCartEntry.getBuyerId())) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			return res;
		}
		//店铺id
		Integer storeId = deleteCartEntry.getStoreId();
		//顾客id(支付宝用户id)
		String buyerId = deleteCartEntry.getBuyerId();
		//桌台名称
		String tableName = deleteCartEntry.getTableName();
		//不清除必选菜
		Integer mustOrder = 1;
		//是否清除未支付订单
		String isClearOrder = deleteCartEntry.getIsClearOrder();
		shopCartService.deleteGoodsCart(storeId,buyerId,tableName,mustOrder,isClearOrder);
		//清除可修改的必选菜（数据库不做删除操作，修改状态为-1）
		shopCartService.updateNeedGoods(storeId,buyerId,tableName);
		res.setSubMsg("购物车已清空了");
		return res;
	}

	@RequestMapping(value = "updateOrDeleteShopCartById", method = RequestMethod.PUT)
	@ResponseBody
	@ApiOperation(value = "根据购物车Id修改购物车中商品购买数量或删除购物车商品(可调用)")
	public CoreResponse<StatusInfo> updateOrDeleteShopCartById(HttpSession session,
			@RequestBody(required=true) UpdateCartEntryVO updateCart) {
		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		if(updateCart==null){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setMsg("updateCart 参数有误");
			return res;
		}
		if(updateCart.getBuyCount()<0){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setMsg("商品购买数量buyCount参数异常");
			return res;
		}
		if(updateCart.getGoodsCartId()==null){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setMsg("购物车Id参数异常");
			return res;
		}
		res = shopCartService.updateOrDeleteShopCartById(updateCart);
		
		return res;
	}

	
	
	@RequestMapping(value = "updateShopCartProp", method = RequestMethod.PUT)
	@ResponseBody
	@ApiOperation(value = "购物车备注页修改商品属性接口（可调用）")
	public CoreResponse<StatusInfo> updateShopCartProp(HttpSession session,
			@RequestBody(required = true) ShopCartPropEntryVO shopCartProp) {
		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		if (shopCartProp.getStoreId() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setMsg("店铺Id参数有误");
			return res;
		}
		
		if (StringUtils.isEmpty(shopCartProp.getBuyerId())) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setMsg("顾客buyerId参数有误");
			return res;
		}
		
		if (shopCartProp.getGoodsCartId() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setMsg("购物车Id为空");
			return res;
		}
		if (shopCartProp.getIsPackage() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setMsg("isPakage参数有误");
			return res;
		}
		if (shopCartProp.getGoodsId() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setMsg("商品id参数有误");
			return res;
		}
		if (shopCartProp.getSizeId() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setMsg("商品规格Id有误");
			return res;
		}
		res = shopCartService.updateShopCartProp(shopCartProp);
		return res;
	}
	
	@RequestMapping(value = "deleteShopCartById", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "购物车页面删除一个商品（可调用）")
	public CoreResponse<Map<String,Object>> deleteShopCartById(HttpSession session,
			@RequestBody(required = true) DeleteShopCartIdEntryVO shopCartIdEntryVO) {
		CoreResponse<Map<String,Object>> res = new CoreResponse<Map<String,Object>>();
		if (shopCartIdEntryVO == null || StringUtils.isEmpty(shopCartIdEntryVO.getBuyerId())
				|| shopCartIdEntryVO.getStoreId() == null || shopCartIdEntryVO.getGoodsCartId() == null){
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("请检查相应参数");
			return res;
		}
		res = shopCartService.deleteShopCartById(shopCartIdEntryVO);
		return res;
	}
}
